<template>
  <div class="demo">
    <div class="demo-title">配合 Form 使用</div>
    <div class="demo-content">
      <Form layout="horizontal">
        <Form.Item
          label="Top coders"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 18 }"
          name="coders"
          v-bind="validateInfos.coders"
        >
          <Mentions v-model:value="modelRef.coders" rows="1">
            <Mentions.Option value="afc163">afc163</Mentions.Option>
            <Mentions.Option value="zombieJ">zombieJ</Mentions.Option>
            <Mentions.Option value="yesmeck">yesmeck</Mentions.Option>
          </Mentions>
        </Form.Item>
        <Form.Item
          label="Bio"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 18 }"
          name="bio"
          v-bind="validateInfos.bio"
        >
          <Mentions
            v-model:value="modelRef.bio"
            rows="3"
            placeholder="You can use @ to ref user here"
          >
            <Mentions.Option value="afc163">afc163</Mentions.Option>
            <Mentions.Option value="zombieJ">zombieJ</Mentions.Option>
            <Mentions.Option value="yesmeck">yesmeck</Mentions.Option>
          </Mentions>
        </Form.Item>
        <Form.Item :wrapper-col="{ span: 12, offset: 5 }">
          <Button type="primary" @click="handleSubmit">Submit</Button>
          <Button style="margin-left: 8px" @click="resetFields">Reset</Button>
        </Form.Item>
      </Form>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { reactive } from 'vue';
  import Form from '@sscd/form';
  import Button from '@sscd/button';
  import Mentions from '@sscd/mentions';
  const { useForm } = Form;
  const { getMentions } = Mentions;
  const checkMention = async (_rule, value) => {
    const mentions = getMentions(value);
    if (mentions.length < 2) {
      return Promise.reject('More than one must be selected!');
    }
    return Promise.resolve();
  };
  const modelRef = reactive({
    bio: '',
    coders: '',
  });
  const rulesRef = reactive({
    bio: [{ required: true, message: 'Must input bio' }],
    coders: [{ required: true, validator: checkMention }],
  });
  const { resetFields, validate, validateInfos } = useForm(modelRef, rulesRef);
  const handleSubmit = (e) => {
    e.preventDefault();
    validate()
      .then(() => console.log('Submit!!!', modelRef))
      .catch((errors) => console.log('Errors in the form!!!', errors));
  };
</script>

<style lang="less" scoped></style>
